<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <el-option value="sfzh" label="身份证号" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="来源:">
        <el-select v-model="query.partsSource" placeholder="请选择" clearable>
          <el-option
            v-for="item in partsSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select
          v-model="user_qtype"
          style="width: 170px; margin-right: 2px;"
          @change="qtypeChange"
        >
          <el-option value="ownerId" label="处理人" />
          <el-option value="transactId" label="下单人" />
        </el-select>
        <el-select
          v-model="user_qtype_value"
          :loading="$loadingPlugin.getOwnerList || $loadingPlugin.getTransactorList"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in userQtypeList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="下单时间" value="transactTime" />
          <el-option label="签收时间" value="signTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
        />
      </el-form-item>
      <!-- <el-form-item label="订单类型:">
        <el-select v-model="query.orderFlagSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderFlagMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态:">
        <el-select
          v-model="query.orderStatusSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select
          v-model="query.csmTypeSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态:">
        <el-select v-model="query.payStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in payStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select
          v-model="query.paymentMethodSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          :loading="$loadingPlugin.fetchData"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="2"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
      @expand-change="expandChange"
    />
    <imageDetails ref="imageDetails" />
    <flow-info ref="flowInfo" />
    <back-goods ref="backGoods" />
    <csm-location ref="csmLocation" />
    <pay-detail ref="payDetail" :payment-method-map="paymentMethodMap" />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <securityOrderInfo ref="securityCheckDetail" :warn-level-map="warnLevelMap" :index-table-data="[]" :tree-data="treeData" />
  </div>
</template>

<script>
  import {
    partsSelect,
    queryOwnerList,
    queryTransactorList,
    queryMap,
    queryExportDomain,
    batchOrderBatchDetail,
    queryCsmInfo,
    partsAll,
    partsDetail
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { csmTypeMap, defaultPaymentMethodMap, orderStatusObj, payStatusObj } from '@/utils/map'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { minDate } from '@/utils/config'
  import { toRMB } from '@/filters'
  import FlowInfo from '../../components/OrderFlowInfoModal'
  import PayDetail from '../orderManage/components/PayDetail'
  import CsmDetail from '../../components/CsmDetailModal/index'
  import imageDetails from './components/imageDetails.vue'
  import BackGoods from './components/backGoods.vue'
  import CsmLocation from '../../components/CsmLocation'
  import securityOrderInfo from '../../safetySupervise/securityOrderManage/components/securityOrderInfo.vue'

  export default {
    name: 'orderManage',
    components: {
      FlowInfo, PayDetail, CsmDetail, imageDetails, BackGoods, CsmLocation, securityOrderInfo
    },
    data() {
      return {
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        partsSourceMap: [
          {
            desc: '配件',
            value: 1
          },
          {
            desc: '即查即改',
            value: 2
          }
        ],
        orderFlagMap: [],
        user_qtype: 'ownerId',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'transactTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        orderStatusMap: [],
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        paymentChannelMap: [],
        paymenFilList: [],
        calcTypeList: [],
        searchParams: {},
        warnLevelMap: [
          { value: 1, desc: '停止供气', key: 'STOPGAS' },
          { value: 2, desc: '限期整改', key: 'XQZG' },
          { value: 3, desc: '立即整改', key: 'LJZG' },
          { value: 4, desc: '有隐患', key: 'YYH' },
          { value: 5, desc: '未安装报警器', key: 'WAZ' },
          { value: 6, desc: '无隐患', key: 'WYH' }
        ],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          partsSource: '',
          orderFlagSource: [0],
          orderStatusSource: [0],
          csmTypeSource: [0],
          payStatus: '',
          paymentMethodSource: [0]
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        },
        goodsInfo: {
          goodsName: '',
          gprince: '',
          gprefPrice: '',
          netWeight: '',
          fee3: '',
          gcount: '',
          fee1: '',
          fee2: '',
          tip: '',
          checkPrice: '',
          fee4: '',
          treceivable: '',
          accReceivable: ''
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            type: 'expand',
            render: (h, { row }) => {
              const partsDetail = row.partsDetail.map(item =>
                (<div class='expand-row'>
                    <div class='row-item row-item1'>{item.goodsName}</div>
                    <div class='row-item'>{item.gprince}</div>
                    <div class='row-item'>{item.gprefPrice}</div>
                    <div class='row-item'>{item.netWeight}</div>
                    <div class='row-item'>{item.fee3}</div>
                    <div class='row-item'>{item.gcount}</div>
                    <div class='row-item'>{item.fee1}</div>
                    <div class='row-item'>{item.fee2}</div>
                    <div class='row-item'>{item.tip}</div>
                    <div class='row-item'>{item.fee4}</div>
                    <div class='row-item'>{item.treceivable}</div>
                    <div class='row-item'>{item.accReceivable}</div>
                  </div>))
              const expandDetail =
                  <div>
                    <div class='expand-row'>
                      <div class='row-item row-item1'>商品</div>
                      <div class='row-item'>单价（元）</div>
                      <div class='row-item'>优惠价格（元）</div>
                      <div class='row-item'>净重</div>
                      <div class='row-item'>回收气量</div>
                      <div class='row-item'>数量</div>
                      <div class='row-item'>配送费</div>
                      <div class='row-item'>上楼费 </div>
                      <div class='row-item'>服务费 </div>
                      <div class='row-item'>优惠金额 </div>
                      <div class='row-item'>应收小计（元）</div>
                      <div class='row-item'>实收小计（元）</div>
                    </div>
                    {partsDetail}
                  </div>
              return (expandDetail)
            }
          },
          {
            prop: 'partsSource',
            label: '来源',
            width: 110,
            formatter: row => {
              return row.partsSource ? row.partsSource === 1 ? '配件' : row.partsSource === 2 ? '即查即改' : '' : ''
            }
          },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110
          },
          {
            prop: 'checkCode',
            label: '关联安检单号',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openSecurityDetail(row, '安检单详情')}>
              {row.checkCode}
            </el-link>
          )
          },
          {
            prop: 'transactor',
            label: '下单人'
          },
          {
            prop: 'ownerName',
            label: '安装人'
          },
          {
            prop: 'ownerCode',
            label: '安装人编号',
            width: 120
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 100
          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
              {row.csmName}
            </el-link>
          )
          },
          {
            prop: 'sfzh',
            label: '身份证号',
            width: 180
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 220,
            render: (h, { row }) => {
              return (
              <span>
                <span class='point-span'>
                  {this.$permission(5) && row.lon && row.lat && (
                    <i
                      onClick={() => this.openLocation(row)}
                      class='linkColor el-icon-location'
                      style='cursor: pointer;'
                    />
                  )}
                  {!this.$permission(5) && (
                    <i class='el-icon-location' style='color:#126edc;cursor: pointer;' />
                  )}
                </span>
                <span>{row.csmAddress}</span>
              </span>
              )
            }
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 130,
            render: (h, { row }) => {
              if (row.contactPhone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.contactPhone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'orderStatus',
            label: '状态',
            sortable: true,
            render: (h, { row }) => (
            <span style={orderStatusObj[row.orderStatus]}>
              {row.orderStatus &&
                formatColumnMap(this.orderStatusMap, 'value', row.orderStatus, 'desc')}
            </span>
          )
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => (
            <span style={payStatusObj[row.payStatus]}>
              {row.payStatus
                ? formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc')
                : '未支付'}
            </span>
          )
          },
          {
            prop: 'signDt',
            label: '签收时间',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.signDt &&
                new Date(row.signDt).getTime() >= new Date(minDate).getTime() &&
                parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'transactTime',
            label: '下单时间',
            sortable: true,
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => (
            <span>
              {row.csmType &&
                formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc')}
            </span>
          )
          },
          {
            prop: 'goodsCount',
            label: '商品总数',
            align: 'right'
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },
          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.decimalSpare4 && row.decimalSpare4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'payWay',
            width: 120,
            label: '支付渠道',
            render: (h, { row }) => <span>{ row.payWay ? formatColumnMap(this.paymentChannelMap, 'value', row.payWay, 'desc') : '' }</span>
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          },
          {
            prop: 'percentage',
            label: '提成'
          },
          {
            label: '照片详情',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openImageDetail(row)}>
               查看
            </el-link>
          )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 80,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      <el-dropdown-item>
                        <el-link v-permission='4' underline={false} size='mini' onClick={() => this.openFlow(row, $index)}>流转信息</el-link>
                      </el-dropdown-item>
                      {row.orderStatus === 10 && row.reStatus !== 2 && (<el-dropdown-item>
                        <el-link
                          v-permission='3'
                          underline={false}
                          size='mini'
                          type='danger'
                          onClick={() => this.openBackGoods(row, $index)}
                        >
                          退货
                        </el-link>
                      </el-dropdown-item>)}
                    </el-dropdown-menu>
                  </el-dropdown>
                  </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.orderFlagSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderFlagSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderFlagSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderFlagSource.length === this.orderFlagMap.length) {
          this.query.orderFlagSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderStatusSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderStatusSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderStatusSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderStatusSource.length === this.orderStatusMap.length) {
          this.query.orderStatusSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.customerTypeMap.length && this.customerTypeMap.length > 1) {
          this.query.csmTypeSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.paymentMethodSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.paymentMethodSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.paymentMethodSource.splice(val.indexOf(0), 1)
        }
        if (this.query.paymentMethodSource.length === this.paymentMethodMap.length && this.paymentMethodMap.length > 1) {
          this.query.paymentMethodSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await Promise.all([
        this.getExportDomain(),
        this.getTreeData(),
        this.getTransactorList(),
        this.getOwnerList(),
        this.queryOptionsMap()
      ])
      this.qtypeChange('ownerId')
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        query[this.user_qtype] = this.user_qtype_value
        if (this.query.orderFlagSource[0] === 0) query.orderFlagSource = []
        if (this.query.orderStatusSource[0] === 0) query.orderStatusSource = []
        if (this.query.csmTypeSource[0] === 0) query.csmTypeSource = []
        if (this.query.paymentMethodSource[0] === 0) query.paymentMethodSource = []
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        const res = await partsSelect(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        this.tableData.data.forEach((item, index) => {
          this.$set(this.tableData.data[index], 'partsDetail', [])
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async expandChange(row) {
        const res = await partsDetail({ orderCode: row.orderCode })
        if (res.data) {
          this.$set(row, 'partsDetail', res.data)
        }
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res8, res9] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayWayType' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value === -1 || item.value === 1 || item.value === 9 || item.value === 10 || item.value === 11 || item.value === 12)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data.filter((item) => item.value !== 32) // 客户类型
        this.payStatusMap = res4.data.filter((item) => item.value !== 4 && item.value !== 6) // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 128) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.paymentChannelMap = res8.data // 支付渠道
        this.calcTypeList = res9.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res4.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
      },
      // 获取处理人列表
      async getOwnerList() {
        const b = (this.corpSettingData.sp1 >> 2) & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data
        if (this.user_qtype === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 处理人或下单人选择
      qtypeChange(value) {
        if (value === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 点击催单次数
      async openPressOrderReport(row) {
        await this.$refs.pressOrderReport.open({ billCode: row.orderCode, billType: 1 })
      },
      // 点击图片
      async showImage(row) {
        await this.$refs.orderImages.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单总额
      async openPayDetail(row) {
        await this.$refs.payDetail.open(row)
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.flowInfo.open(row.orderCode)
      },
      // 点击退货
      async openBackGoods(row) {
        await this.$refs.backGoods.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击查看图片
      async openImageDetail(row) {
        await this.$refs.imageDetails.open(row.orderCode)
      },
      // 安检详情
      async openSecurityDetail(row, type) {
        const r = {
          ...row,
          checkId: row.checkCode
        }
        await this.$refs.securityCheckDetail.open(r, type)
      },
      // 查看
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          if (this.date && this.date.length === 2) {
            params[this.dateType] = this.date[0]
            params[`${this.dateType}End`] = this.date[1]
          }
          partsAll({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 1) {
          return 'danger-row'
        }
        if (row.orderStatus === 12) {
          return 'warn-row'
        }
        return ''
      },
      async tryPrint(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await batchOrderBatchDetail(params)
        if (status === 200) {
          this.tryPrint1(row, data)
        }
      },
      async tryPrint1(row, resdata) {
        const params = {
          csmCode: row.csmCode
        }
        const { status, data } = await queryCsmInfo(params)
        if (status === 200) {
          row['lastBuyDt'] = data['lastBuyDt'] || ''
          row['score'] = data['score'] || 0
          this.print(row, resdata)
        }
      },
      print(row, resdata) {
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['1']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        row.printDt = parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')
        row.printMoney = `${row.treceivables}(${toRMB(row.treceivables)})`
        if (row.payStatus === 3) {
          row.printMoney = `${row.printMoney} 已支付(${formatColumnMap(
            this.paymentMethodMap,
            'value',
            row.payMethod,
            'desc'
          )})`
        }
        row.csmAddress = row.csmAddress.replace(
          /([\u4E00-\u9FA5]*)([省市])(\s*)([\u4E00-\u9FA5]*)市/g,
          ''
        )
        row.payMethod = ''
        for (var item in this.paymentMethodMap) {
          if ((item & row.paymentMethodMap) > 0) {
            row.payMethod += this.paymentMethodMap[item].desc + ','
          }
        }

        row.payMethod = (row.payMethod || '').replace(/(^,+)|(,+$)/g, '')
        row.csmTypeName =
          formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') || '居民用户'

        let printcmd = {
          cmd: 2,
          title: `正在对订单${row.orderCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }

        // let tmpbl =
        //   row.corpCode == "44011" &&
        //   /^[\d]{1,}20$/.test(row.orderCode) &&
        //   dayjs(row.transactDt).format('YY-MM-DD') == "17-11-26";
        if (!window.jCPrint || !window.jCPrint.ws) {
          this.$message.error('打印未连接')
          return
        }
        if (row.csmType) row.csmType = csmTypeMap[row.csmType] // 处理用户类型
        if (row.paymentMethod) row.paymentMethod = defaultPaymentMethodMap[row.paymentMethod] // 处理结算方式
        if (row.transactTime) row.transactTime = moment(row.transactTime).format('YYYY-MM-DD') // 处理下单时间
        if (row.dateTimeSpare3) row.dateTimeSpare3 = moment(row.dateTimeSpare3).format('YYYY-MM-DD') // 处理派单时间
        if (row.transactTime) row.transactTime = moment(row.transactTime).format('YYYY-MM-DD') // 处理制单时间
        window.jCPrint.process(printcmd, temp, row, resdata)
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffeced;
}
/deep/ .el-table tr.giveup-row {
  background: #ffeced;
}
/deep/ .el-table tr.warn-row {
  background: #FC9;
}
/deep/.expand-row {
  display: flex !important;
  width: 100% !important;
  .row-item {
    width: 150px;
    line-height: 30px;
    text-align: center;
  }
  .row-item1 {
    margin-left: 100px;
  }
}
</style>
